<template>
  <BasicLayout>
    <template #wrapper>
      <search-form label-width="62px" operate-float="left" :form-config="formConfig" :handler="handler" :form-data="formData" @onSubmit="onSubmit" />
      <table-pagination
        class="table"
        :loading="loading"
        :columns="columns"
        :data="tableData"
        :height="tableHeight"
        :total="count"
        :page="currentPage"
        border
        @handlePaginationChange="handleCurrentChange"
      >
        <template slot="department" slot-scope="scope"><span>{{ scope.item.department?scope.item.department.fullName:scope.item.department }}</span></template>
        <template slot="userState" slot-scope="scope">
          <el-switch
            v-model="scope.item.userState"
            active-text="开启"
            inactive-text="禁用"
            @change="handleUserState(scope.item)"
          />
        </template>
        <template slot="operate" slot-scope="scope">
          <el-link
            type="primary"
            :underline="false"
            @click="handleEdit(scope.item)"
          >编辑</el-link>
          <el-link
            type="primary"
            :underline="false"
            :style="{'margin-left': '10px'}"
            @click="handleDelete(scope.item)"
          >删除</el-link>
        </template>
      </table-pagination>
      <el-button icon="el-icon-circle-plus-outline" size="small" type="success" @click="handleAdd">添加</el-button>
      <el-button icon="el-icon-upload2" size="small" type="primary" @click="importFileVisible = true">导入</el-button>
      <import-file
        ref="importFileRef"
        :visible="importFileVisible"
        :download-error-data-show="false"
        :pagination-show="false"
        :width="'800px'"
        :file-size="10"
        :desc-info="descInfo"
        :error-columns="errorColumns"
        @close="importFileVisible = false"
        @downLoadTemplateFile="downLoadTemplateFile"
        @firstImport="firstImport"
        @isImport="isImport"
      />
    </template>
  </BasicLayout>
</template>

<script>
import SearchForm from '@/components/common/SearchForm';
import TablePagination from '@/components/common/TablePagination';
import ImportFile from '@/components/common/ImportFile';
import { getUserList, userUpdate, userDelete, selectRoleList, downloadUserTemplate, preImportUser, importUser } from '@/api/staffApi';
import { judgeResponseType } from '@/utils/tools';
import { exportFile } from '@/utils/tools';
import { getDepartmentTree } from '@/api/commonApi';
import config from './config';

export default {
  name: 'StaffManagement',
  components: {
    SearchForm,
    TablePagination,
    ImportFile
  },
  data() {
    return {
      formConfig: config.formConfig,
      columns: config.columns,
      errorColumns: config.errorColumns,
      tableData: [],
      loading: false,
      importFileVisible: false,
      count: 0,
      currentPage: 1,
      pageSize: 20,
      formData: {
        name: null,
        roles: null,
        department: null
      },
      formCopy: {}, // 拷贝搜索栏查询数据
      handler: [
        { label: '查询', prop: 'submit', type: 'primary', eventName: 'onSubmit', icon: 'el-icon-search' },
        { label: '重置', prop: 'reset', type: 'default', eventName: 'onReset', icon: 'el-icon-refresh-right' }
      ],
      fileData: null,
      descInfo: {
        0: '填写导入员工的信息',
        1: '上传填好的员工信息表',
        2: '本次可导入员工数量',
        3: '本次不可导入员工数量',
        4: '不可导入员工列表',
        5: '成功导入员工数量',
        6: '人',
        7: '人'
      }
    };
  },
  inject: ['getTableHeight', 'getSearchPanel', 'countTableHeght'],
  computed: {
    tableHeight() {
      return this.getTableHeight();
    },
    searchPanel() {
      return this.getSearchPanel();
    }
  },
  watch: {
    searchPanel: {
      deep: true,
      handler() {
        this.$nextTick(() => this.countTableHeght(0));
      }
    }
  },
  mounted() {
    this.onGetDepartmentTree();
    this.onGetSelectRoleList();
    this.onGetUserList({}, this.formData);
  },
  methods: {
    // 获取部门数据
    onGetDepartmentTree() {
      getDepartmentTree().then(({ data }) => {
        this.formConfig[2].options = [data];
      });
    },
    // 获取角色数据
    onGetSelectRoleList() {
      selectRoleList().then(({ data }) => {
        this.formConfig[1].options = data.map(item => ({ name: item.name, value: item.id }));
      });
    },
    // 点击查询
    onSubmit(form) {
      this.onGetUserList({ pageNo: 1, pageSize: this.pageSize }, form);
    },
    // 获取员工管理列表数据
    onGetUserList({ pageNo = 1, pageSize = 10 }, form = {}) {
      this.formCopy = JSON.parse(JSON.stringify(form));
      this.loading = true;
      this.currentPage = pageNo;
      this.pageSize = pageSize;
      getUserList({
        ...form,
        name: form.name === '' ? null : form.name,
        pageNo,
        pageSize
      }).then((res) => {
        this.loading = false;
        this.tableData = res.data;
        this.tableData.map(item => {
          item.userGender = item.userGender === 'MALE' ? '男' : '女';
          item.userState = item.userState === 'ENABLE' ? true : 0;
          if (item.roles) {
            item.roles = item.roles.map(item => item.name).join(',');
          }
        });
        if (this.currentPage === 1) { this.count = res.total; }
      });
    },
    // 编辑员工
    handleAdd() {
      this.$router.push({ name: 'staffDataOperation' });
    },
    // 编辑员工
    handleEdit({ userId }) {
      this.$router.push({ name: 'staffDataOperation', query: { userId: this.CryptoJS.AES.encrypt(String(userId), 'userId').toString() }});
    },
    // 删除员工
    handleDelete({ userId }) {
      this.$alert('是否确定删除员工？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true
      }).then(() => {
        userDelete(userId).then((res) => {
          this.$message.success('已删除！');
          this.onGetUserList({ pageNo: this.currentPage }, this.formCopy);
        });
      });
    },
    // 改变员工状态
    handleUserState({ userId, userState }) {
      userUpdate({ userId, userState: userState ? 'ENABLE' : 'DISABLE' }).then((res) => {
        this.$message.success('状态更新成功！');
        // this.onGetUserList({ pageNo: this.currentPage }, this.formCopy);
      });
    },
    handleCurrentChange({ current, size }) {
      this.onGetUserList({ pageNo: current, pageSize: size }, this.formCopy);
    },
    // 下载员工信息导入模板
    downLoadTemplateFile() {
      downloadUserTemplate().then(res => {
        judgeResponseType(res).then(() => {
          // 说明是正常的文件流
          exportFile(res, '员工信息导入模板.xlsx');
        }).catch(error => {
          this.$message.error(error.resultMessage || '请求异常');
        });
      });
    },
    // 重新上传 或者 确认导入
    isImport(proceed) {
      if (!proceed) {
        // 重新上传
        this.$refs.importFileRef.resetData();
        this.$refs.importFileRef.resetStatus();
        return false;
      }
      // 确认导入
      importUser(this.fileData, this.$refs.importFileRef.onUploadProgress).then(res => {
        this.$refs.importFileRef.toThird(res.data.success || 0);
      }).catch(() => {
        this.$refs.importFileRef.resetData();
      }).finally(() => {
        this.$refs.importFileRef.resetStatus();
      });
    },
    // 导入文件后台解析 点击下一步触发
    firstImport(formData) {
      preImportUser(formData, this.$refs.importFileRef.onUploadProgress).then(res => {
        this.fileData = formData;
        this.$refs.importFileRef.toSecond({
          errorNum: res.data.fail,
          correctNum: res.data.success
        });
        if (res.data.fail > 0) {
          this.$refs.importFileRef.setErrorTableData(
            1,
            res.data.userImportRspItems
          );
        }
      }).catch(() => {
        this.$refs.importFileRef.resetProgress();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.table{
  margin: 20px 0;
}
</style>
